package org.sauceggplant;

import java.util.Base64;

/**
 * 字节数组实用类
 *
 * @author jacob
 * @version 0.1
 */
public class ByteUtil {

    public static String toBase64(byte[] bytes) {
        return Base64.getEncoder().encodeToString(bytes);
    }

    public static byte[] fromBase64(String base64) {
        return Base64.getDecoder().decode(base64);
    }

    public static byte[][] split(byte[] data, int blockSize) {
        int blocks = (data.length % blockSize == 0) ? (data.length / blockSize) : (data.length / blockSize + 1);
        byte[][] result = new byte[blocks][];
        byte[] buffer;
        int index = 0, offset = 0;
        while (data.length > offset) {
            if (index == blocks - 1) {
                buffer = new byte[data.length - offset];
            } else {
                buffer = new byte[blockSize];
            }
            System.arraycopy(data, offset, buffer, 0, buffer.length);
            result[index] = buffer;
            index++;
            offset += buffer.length;
        }
        return result;
    }
}
